//
//  WBStatusDAL.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/2/12.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import Foundation

/// DAL - Data Access Layer,数据访问层
/// 负责处理数据库和网络数据,给listViewModel返回微博的字典数组
/// 在调整系统的时候,尽量做最小化的调整
class WBStatusDAL {
    
    
    /// 从本地数据库或者网络加载数据
    ///
    /// - Parameters:
    ///   - since_id: 下拉刷新
    ///   - max_id: 上拉刷新
    ///   - completion: 回调方法(list: 微博字典数组, isSuccess: 是否成功)
    class func loadStatus(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String: Any]]?, _ isSuccess: Bool) -> ()) {
        
        // 1.检查本地数据,如果有,直接返回
        
        // 1.1获取userId
        guard let userId = SSWBNetworkManager.shared.userAccount.uid else {
            return
        }
        
        let array = SSSQLiteManager.shared.loadStatus(userId: userId, since_id: since_id, max_id: max_id)
        
        // 1.2判断数组的数量
        if array.count > 0 {
            
            completion(array, true)
            return
        }
        
        // 2.如果没有,加载网络数据
        SSWBNetworkManager.shared.statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            if !isSuccess {
                completion(nil, false)
                return
            }
            
            // 判断数据
            guard let list = list else {
                completion(nil, isSuccess)
                return
            }
            
            // 3.加载完成之后,将网络数据同步写入数据库
            SSSQLiteManager.shared.updateStatus(userId: userId, array: list)
            
            // 4.返回网络数据
            completion(list, isSuccess)
        }
        
        
    }
}
